﻿using System;
using System.Collections.Generic;
using Engine.Math;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Engine.Objects.StaticObjects
{
    [Serializable]
    public class StaticObject
    {
        #region Fields

        private string _modelAssetName;

        #endregion
        #region Properties

        [NonSerialized]
        private Model _model;        
        public Model Model
        {
            get { return _model; }
            private set { _model = value; }
        }

        private Vector3 _scale = Vector3.One;
        public Vector3 Scale
        {
            get { return _scale; }
            set 
            { 
                _scale = value;
                Update();
            }
        }
        private Vector3 _translation;
        public Vector3 Translation
        {
            get { return _translation; }
            set
            {
                _translation = value;
                Update();
            }
        }
        public Matrix WorldMatrix { get; set; }
        public BoundingBox InitialBoundingBox
        {
            get
            {
                var tag = (Dictionary<string, object>) Model.Tag;
                return (BoundingBox) tag["BoundingBox"];
            }
        }

        [NonSerialized] 
        private bool _visible = true;
        public bool Visible
        {
            get { return _visible; }
            set { _visible = value; }
        }

        #endregion

        #region Public Methods

        public void ReloadModel(Game game)
        {
            LoadModel(game,_modelAssetName);
        }
        public void LoadModel(Game game, string assetName)
        {
            _modelAssetName = assetName;
            Model = game.Content.Load<Model>(assetName);            
        }
        public bool Contains(Vector3 position)
        {
            BoundingBox boundingBox = InitialBoundingBox.Transform(WorldMatrix);
            return boundingBox.Contains(position) != ContainmentType.Disjoint;
        }
        virtual public float? Interescts(Ray ray)
        {
            BoundingBox boundingBox = InitialBoundingBox.Transform(WorldMatrix);
            return boundingBox.Intersects(ray);
        }
        virtual public bool Interescts(BoundingBox boundingBox)
        {
            BoundingBox transformedBoundingBox = InitialBoundingBox.Transform(WorldMatrix);
            return transformedBoundingBox.Contains(boundingBox) != ContainmentType.Disjoint;
        }

        #endregion

        #region Private methods
     
        #endregion

        #region Public methods

        public void Update()
        {
            WorldMatrix = Matrix.CreateScale(Scale) * Matrix.CreateTranslation(Translation);
        }

        #endregion      
    }
}
